# pythonchallenge.com scripts
# challenge #4
# url: http://www.pythonchallenge.com/pc/def/linkedlist.php

import urllib
import re

url_base = 'http://www.pythonchallenge.com/pc/def/linkedlist.php?'
nval = '12345'
llnum = 400
VAL_LIST = []

# cycle llnum times (hint suggests 400)
while llnum > 0:
  
  # store nval in list (VAL_LIST)
  VAL_LIST.append(nval)
  
  # build url (curl): url_base + nval
  curl = url_base + nval
  print nval + ' : ' + curl
  
  # get source for curl
  prm = urllib.urlencode({'nothing': nval})
  f = urllib.urlopen(url_base + prm)
  src = f.read()
  if src == '' :
    break
  
  # parse nothing value (nval): and the next nothing is /\s+([^\s]+)/
  re1 = 'and the next nothing is\s+([^\s]+)'
  Match = re.compile(re1).search(src)
  try:
    nval = Match.group(1)
  except AttributeError:
    print 'parse failed -> break'
    break
  
  # edge cases
  if nval == '92118':
    print 'edge () '
    nval = str(int(nval) / 2)
  
  # check nval against last value in VAL_LIST:
  # if match: stop
  if nval == VAL_LIST[len(VAL_LIST)-1]:
    break
    
  # else: rinse and repeat
  llnum -= 1

    
# print last n in VAL_LIST
ln = 5
while ln > 0:
  print VAL_LIST.pop()
  ln -= 1
  

# print source of last url
print '\nsource:\n' + src
  
